package com.yyi.springcloud.utils;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.PeriodType;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * joda操作时间的工具类
 */
public class JodaTimeUtil {
    // 计算两个时间相差多少天
    public static int howLongDays(String startTime,String endTime) {
        if (startTime == null) {
            return Integer.MAX_VALUE;
        }
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
            Date d1 = format.parse(startTime);
            Date d2 = format.parse(endTime);
            Period p = new Period(new DateTime(d1), new DateTime(d2), PeriodType.days());
            System.out.println("相隔的天：" + p.getDays());
            return p.getDays();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return Integer.MAX_VALUE;
    }

    // 计算两个时间相差多少秒
    public static int howLongSecond(String startTime,String endTime) {
        if (StringUtils.isEmpty(startTime)||StringUtils.isEmpty(endTime)) {
            return Integer.MAX_VALUE;
        }
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date d1 = format.parse(startTime);
            Date d2 = format.parse(endTime);
            Period p = new Period(new DateTime(d1), new DateTime(d2), PeriodType.seconds());
            System.out.println("相隔的秒：" + p.getSeconds());
            return p.getSeconds();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return Integer.MAX_VALUE;
    }

    // 计算两个时间相差多少秒
    public static int howLongHour(String startTime,String endTime) {
        if (startTime == null) {
            return Integer.MAX_VALUE;
        }
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date d1 = format.parse(startTime);
            Date d2 = format.parse(endTime);
            Period p = new Period(new DateTime(d1), new DateTime(d2), PeriodType.hours());
            System.out.println("相隔的小时：" + p.getHours());
            return p.getHours();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return Integer.MAX_VALUE;
    }

    public static void main(String[] args) {
        howLongDays("2017/11/06","2017/11/07");
        howLongSecond("2018-06-13 17:07:11","2018-06-13 17:07:51");
        howLongHour("2018-06-13 17:07:11","2018-06-13 17:07:51");

    }
}
